package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Author: wenjingyuan
 * @Date: 2023/03/28/17:32
 * @Description:通过aid拿到用户的详细信息
 */
@WebServlet("/getuserbyaid")
public class GetUserByAid extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg="未知错误！";
        UserInfo userInfo=new UserInfo();
        //1.得到前端的信息并进行校验
        String aidStr=req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)){
            int aid=Integer.valueOf(aidStr);
            if(aid>0){
                //2.在查询数据库中找到用户的详情
                //查询用户的信息
                Connection connection= DBUtils.getConnection();
                String sql="select * from userinfo where uid=(select uid from article where aid=?)";
                PreparedStatement statement= connection.prepareStatement(sql);
                statement.setInt(1,aid);
                ResultSet resultSet=statement.executeQuery();
                if(resultSet.next()){
                    userInfo.setUid(resultSet.getInt("uid"));
                    userInfo.setNickname(resultSet.getString("nickname"));
                    userInfo.setImg(resultSet.getString("img"));
                }
                //查询用户发表的所有文章数
                sql="select count(*) as account from article  where uid=(select uid from article where aid=?)";
                PreparedStatement statement2= connection.prepareStatement(sql);
                statement2.setInt(1,aid);
                ResultSet resultSet2=statement2.executeQuery();
                if(resultSet2.next()){
                    userInfo.setAccount(resultSet2.getInt("account"));
                }
                msg="成功！";
                //关闭资源
                DBUtils.close(resultSet2,statement2,null);
                DBUtils.close(resultSet,statement,connection);
            }else{
                msg="非法参数";
            }
        }else{
            msg="非法参数";
        }


        //3.将后端得到的参数返回给前端
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,userInfo,msg)));
    }
}
